const Router = require("@koa/router");
const router = new Router();
const startConnect = require("../db");
const {
  verifyToken
} = require("../core/util");
const {
  mutateExecOptions
} = require("nodemon/lib/config/load");

//查看是否已预约该阅览室
router.post("/has_appointment", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      id
    } = isValid;
    const {
      room_id
    } = ctx.request.body;

    const sql = `select id from appointment where user_id = '${id}' and room_id = '${room_id}' and state ='待签到'`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res[0] ? true : false,
      };
      console.log("hasUser");
    });
  } else {
    ctx.body = 404;
  }
});

//获取座位在该时间段的预约情况
router.get("/seat_state", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      id
    } = isValid;
    const {
      room_id,
      start_time,
      end_time
    } = ctx.request.query;
    const sql =
      "select type,`row`" +
      `,col,idx from appointment where ('${start_time}'   between start_time and end_time  or  '${end_time}'  between start_time and  end_time)  and room_id ='${room_id}' `;

    await startConnect(sql).then((res) => {
      if (res[0]) {
        ctx.body = {
          tag: res[0] ? true : false,
          data: res,
        };
      } else {
        ctx.body = {
          tag: false,
        };
      }
    });
  } else {
    ctx.body = 404;
  }
});

//获取用户在该时间段是否已有预约
router.get("/has_appointment_in_time", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      id
    } = isValid;
    const {
      start_time,
      end_time,
      date,
      appointment_id
    } = ctx.request.query;
    const sql =
      "select type,`row`" +
      `,col,idx from appointment where ('${start_time}'   between start_time and end_time  or  '${end_time}'  between start_time and  end_time) and user_id ='${id}' and state ='待签到' and date = '${date}' and id != '${appointment_id}'`;
    await startConnect(sql).then((res) => {
      console.log('获取用户在该时间段是否已有预约', sql, res);
      if (res[0]) {
        ctx.body = {
          tag: res[0] ? true : false,
        };
      } else {
        ctx.body = {
          tag: false,
        };
      }
    });
  } else {
    ctx.body = 404;
  }
});

//获取该阅览室在该时间段是否已被其他人预约
router.get("/has_appointment_by_other", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      id
    } = isValid;
    const {
      start_time,
      end_time,
      date,
      room_id,
      appointment_id
    } = ctx.request.query;
    const sql =
      "select type,`row`" +
      `,col,idx from appointment where ('${start_time}'   between start_time and end_time  or  '${end_time}'  between start_time and  end_time)  and date ='${date}' and room_id='${room_id}' and state ='待签到' and id !='${appointment_id}'`;

    await startConnect(sql).then((res) => {

      console.log('获取该阅览室在该时间段是否已被其他人预约', sql, res);
      if (res[0]) {
        ctx.body = {
          tag: res[0] ? true : false,
        };
      } else {
        ctx.body = {
          tag: false,
        };
      }
    });
  } else {
    ctx.body = 404;
  }
});

//评价回复
router.post("/judge_answer", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      feedback_id,
      rate
    } = ctx.request.body;
    const {
      id
    } = isValid;

    //更新预约信息

    const sql = `update feedback set rate = '${rate}',confirm=${true} where id = '${feedback_id}' and user_id ='${id} '`;

    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows ? true : false,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//获取预约信息
router.get("/appointment", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      id
    } = isValid;

    let updateState = `update appointment set state ='已过期' where  CURRENT_TIMESTAMP  > end_time `;
    const sql = `SELECT a.id,a.state,a.date,a.start_time,a.end_time,a.type,a.row,a.col,a.idx,e.id as room_id,e.open,e.name,e.located,e.open_time FROM appointment AS a, reading_rooms AS e WHERE a.user_id = '${id}' and a.room_id = e.id`;

    await startConnect(updateState).then(async () => {
      await startConnect(sql).then((res) => {
        if (res[0]) {
          res.for;
          ctx.body = {
            tag: res[0] ? true : false,
            data: res,
          };
        } else {
          ctx.body = {
            tag: false,
          };
        }
      });
      console.log("获取预约信息", sql);
    });
  } else {
    ctx.body = 404;
  }
});

//预约阅览室
router.post("/make_appointment", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      start_time,
      end_time,
      room_id,
      type,
      row,
      col,
      idx,
      date
    } =
    ctx.request.body;
    const {
      id
    } = isValid;

    //更新预约信息

    const sql =
      "insert into appointment(user_id, room_id, type, `row`" +
      `, col, idx, date, start_time, end_time)  values('${id}','${room_id}','${type}','${row}','${col}','${idx}','${date}','${start_time}','${end_time}')`;

    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows ? true : false,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//取消预约
router.post("/cancel_appointment", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      appointment_id,
      room_id
    } = ctx.request.body;
    const {
      id
    } = isValid;

    //取消预约
    const sql = `delete from appointment where id = '${appointment_id}' and user_id = '${id}' and state ='待签到'`;
    console.log("cancel_appointment", sql);

    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows ? true : false,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//更改时间
router.post("/change_date", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      appointment_id,
      date,
      startTime,
      endTime
    } = ctx.request.body;
    const {
      id
    } = isValid;
    //更改时间
    const sql = `update appointment set date ='${date}', start_time ='${startTime}', end_time ='${endTime}' where id='${appointment_id}' and user_id = '${id}' and state ='待签到'`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows ? true : false,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//获取已预约有效数量 get_appointment_num
router.get("/get_appointment_num", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      id
    } = isValid;
    //获取已预约数量
    const sql = `SELECT COUNT(id) as num FROM appointment where user_id ='${id}' and state ='待签到'  `;
    await startConnect(sql).then((res) => {
      if (res[0]) {
        ctx.body = {
          tag: true,
          data: res,
        };
      } else {
        ctx.body = {
          tag: false,
        };
      }
    });
  } else {
    ctx.body = 404;
  }
});

//意见反馈
router.post("/post_feedback", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      content
    } = ctx.request.body;
    const {
      id
    } = isValid;
    //更改时间
    const sql = `insert into feedback(user_id,feedback_content) values('${id}','${content}')`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows ? true : false,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//获取意见反馈
router.get("/get_my_feedback", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      id
    } = isValid;
    //获取已预约数量
    const sql = `SELECT *  FROM feedback where user_id ='${id}'  `;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: true,
        data: res,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//获取基本信息
router.get("/get_info", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      id
    } = isValid;
    //更改时间
    const sql = `select username,sex,email,phone from user where id ='${id}'`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res[0] ? true : false,
        data: res[0],
      };
    });
  } else {
    ctx.body = 404;
  }
});

//更改基本信息
router.post("/update_info", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      sex,
      phone,
      email
    } = ctx.request.body;
    const {
      id
    } = isValid;
    //更改时间
    const checkEmail = `select id from user where email ='${email}' and id !='${id}'`;
    const checkPhone = `select id from user where phone ='${phone}' and id !='${id}'`;
    const sql = `update user set sex ='${sex}',phone ='${phone}',email ='${email}' where id= '${id}' `;

    await Promise.all([
      startConnect(checkEmail),
      startConnect(checkPhone),
    ]).then(async (res) => {
      let invalidFiled = res[0][0] ? "邮箱" : "";
      invalidFiled += res[1][0] ? (invalidFiled ? "、手机号" : "手机号") : "";
      if (invalidFiled.length) {
        ctx.body = {
          tag: false,
          msg: `${invalidFiled}与其他用户冲突`,
        };
      } else {
        await startConnect(sql).then((res) => {
          ctx.body = {
            tag: res.affectedRows ? true : false,
          };
        });
      }
    });
  } else {
    ctx.body = 404;
  }
});

//签到
router.post("/signin", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 0) {
    const {
      appointment_id
    } = ctx.request.body;
    const {
      id
    } = isValid;
    //更改时间
    const sql = `select id from appointment where CURRENT_TIMESTAMP  between start_time and end_time  and id ='${appointment_id}' and user_id ='${id}' and state ='待签到'`;

    await startConnect(sql).then(async (res) => {
      if (res[0]) {
        let sql = `update appoiment set state = '已签到' where id ='${appointment_id}' and user_id ='${id}'`;

        await startConnect(sql).then((res) => {
          ctx.body = {
            tag: res.affectedRows ? true : false,
            msg: res.affectedRows ? "签到成功" : "签到失败",
          };
        });
      } else {
        ctx.body = {
          tag: res[0] ? true : false,
          msg: "当前非签到时间",
        };
      }
    });
  } else {
    ctx.body = 404;
  }
});

module.exports = router;